<?php

define('DOC_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once DOC_ROOT . '/src/php/Utils.php';
require_once DOC_ROOT . '/src/php/Config.php';

// 获取一系列请求参数
$rq = PUtil::getParams(array('path', 'file_name', 'index', 'title', 'title_tip', 'title_desc', 'arguments', 'arguments_name', 'arguments_desc', 'attributes', 'attributes_name', 'attributes_desc', 'methods', 'methods_name', 'methods_desc', 'return', 'return_desc', 'code'));

if($rq['file_name'] == ''){
    echo json_encode(array(
        'ret' => -1,
        'msg' => 'Lack parameters!',
    ));
    exit();
}

// 保存到数据库
$saveData = array(
    'p_path' => $rq['path'],
    'p_filename' => $rq['file_name'],
    'p_index' => $rq['index'],
    'p_title' => $rq['title'],
    'p_titletip' => $rq['title_tip'],
    'p_titledesc' => $rq['title_desc'],
    'p_arguments' => $rq['arguments'],
    'p_argumentsdesc' => PUtil::disposeList($rq['arguments_name'], $rq['arguments_desc']),
    'p_attributes' => $rq['attributes'],
    'p_attributesdesc' => PUtil::disposeList($rq['attributes_name'], $rq['attributes_desc']),
    'p_methods' => $rq['methods'],
    'p_methodsdesc' => PUtil::disposeList($rq['methods_name'], $rq['methods_desc']),
    'p_return' => $rq['return'],
    'p_returndesc' => $rq['return_desc'],
//    'p_returndesc' => htmlentities(addslashes($rq['return_desc']), ENT_QUOTES),
    'p_code' => addslashes($rq['code']),
);

if (PUtil::saveDoc(PConfig::$tablecn[$rq['path']], $saveData, 'p_filename="' . $saveData['p_filename'] . '"')) {
    echo json_encode(array(
        'ret' => 0,
        'msg' => 'Success!',
    ));
} else {
    echo json_encode(array(
        'ret' => -1,
        'msg' => 'Failure!',
    ));
}


// 对生成的文件名添加序号——用于生成树状导航用
$rq['file_name'] = $rq['index'] . $rq['file_name'];
// 对code域进行关键字高亮
$rq['code'] = PUtil::replaceKeys(PConfig::$codeKeyMatch, $rq['code']);

// smarty方式创建html
smartyNewFile(DOC_ROOT, $rq);

// php方式创建html
//newFile($root, $rq);

/* ================================= */
/* ==smarty方式 创建HTML文件模板=== */
/* ================================= */

function smartyNewFile($root, $rq) {
    require_once $root . '/src/php/Index.php';
    $instance = new PIndex();

    // 模板url根路径
    $rq['url_prefix'] = toRelativePath($rq['path']);

    $file = fopen($root . $rq['path'] . '/' . iconv("UTF-8", "GBK", $rq['file_name']) . '.html', 'w');

    fwrite($file, $instance->fetchAction('api_tpl.tpl', $rq));
    fclose($file);
}

function toRelativePath($str) {
    $count = count(explode('/', str_replace('/api_doc/', '', $str)));
    $rs = '';
    while ($count > 0) {
        $rs = $rs . '../';
        $count--;
    }
    return $rs;
}

/* ================================= */
/* ====php方式 创建HTML文件模板==== */
/* ================================= */

function newFile($root, $rq) {
    $file = fopen($root . $rq['path'] . '/' . $rq['file_name'] . '.html', 'w');

    // 组织数据
    $data = array(
        'title' => array($rq["title"], $rq['title_tip'], $rq['title_desc']),
        'return' => array($rq["return"], '', $rq['return_desc']),
        'code' => $rq['code'],
        'arguments' => array($rq['arguments'], toAssoArray($rq['arguments_name'], $rq['arguments_desc'])),
        'methods' => array($rq['methods'], toAssoArray($rq['methods_name'], $rq['methods_desc'])),
        'attributes' => array($rq['attributes'], toAssoArray($rq['attributes_name'], $rq['attributes_desc'])),
    );

    fwrite($file, newHtmlWrapper($data));
    fclose($file);
}

function toAssoArray($aryN, $aryV) {
    if (is_array($aryN) && is_array($aryV) && count($aryN) != count($aryV) && count($aryN) == 0) {
        return array();
    } else {
        $i = 0;
        $l = count($aryN);
        $rs = array();
        while ($i < $l) {
            array_push($rs, array(
                'name' => $aryN[$i],
                'desc' => $aryV[$i],
            ));
            $i++;
        };
        return $rs;
    }
}

function newHtmlWrapper($data) {
    $html = '<!DOCTYPE html>
                    <html>
                        <head>
                            <title></title>
                            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                            <link type="text/css" rel="stylesheet" href="../../resource/css/reset.css"/>
                            <link type="text/css" rel="stylesheet" href="../../resource/css/api_index.css"/>
                            <script type="text/javascript" src="../../resource/js/fw/jquery-1.8.3.min.js"></script>
                            <script type="text/javascript" src="../../resource/js/api_index.js"></script>
                        </head>
                        <body><div class="pk-wrap">';
    $body = '';
    foreach ($data as $k => $v) {
        switch ($k) {
            case 'title' :
            case 'return' :
                $body = $body . newDescModule($v[0], $v[1], $v[2]);
                break;
            case 'arguments' :
            case 'attributes' :
            case 'methods' :
                $body = $body . newTableModule($v[0], $v[1]);
                break;
            case 'code' :
                $body = $body . newCodeModule($v);
                break;
        }
    }
    $html = $html . $body . '</div></body></html>';
    return $html;
}

function newDescModule($title, $titleTip, $titleDesc) {
    if ($title == '' || $titleTip == '' || $titleDesc == '') {
        return '';
    } else {
        return '<div class="pk-unit-wrap">
                    <div class="pk-unit">
                        <h1 class="clearfix">
                            <span class="pk-color-title">' . $title . '</span>
                            <span class="pk-float-right pk-tip">' . $titleTip . '</span>
                        </h1>
                    </div>
                    <div class="pk-unit">
                        <div class="pk-unit-with-style">
                            <div class="pk-unit-tag">Description</div>
                            <pre>' . $titleDesc . '</pre>
                        </div>
                    </div>
                </div>';
    }
}

function newTableModule($title, $list) {
    if ($title == '' || count($list) == 0) {
        return '';
    } else {
        $tmp = '';
        foreach ($list as $itm) {
            $tmp = $tmp . '<tr>
                                <td>' . $tmp['name'] . '</td>
                                <td>' . str_replace("\r\n", "<br/>", $tmp['desc']) . '</td>
                            </tr>';
        }
        $tpl = '<div class="pk-unit-wrap">
                <div class="pk-unit">
                    <h1 class="clearfix">
                        <span class="pk-color-title pk-italic">' . $title . '</span>
                    </h1>
                </div>
                <div class="pk-unit">
                    <table>
                        <thead>
                            <tr>
                                <th class="pk-w120">Name</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>' . $tmp . '</tbody>
                    </table>
                </div>
            </div>';
        return $tpl;
    }
}

function newCodeModule($code) {
    if ($code == '') {
        return '';
    } else {
        return '<div class="pk-unit-wrap">
                <div class="pk-unit">
                    <h1 class="clearfix">
                        <span class="pk-color-title">代码示例</span>
                    </h1>
                </div>
                <div class="pk-unit">
                    <div class="pk-unit-with-style">
                        <div class="pk-unit-tag">Code</div>
                        <div>' . $code . '</div>
                    </div>
                </div>
            </div>';
    }
}